<template>
	<view class="flex-col group_1">
		<view class="flex-col">
			<view class="flex-col text-wrapper">
				<text class="text_1">需付金额：￥{{order.total_fee/100.0}}</text>
			</view>
			<view class="flex-col section_1">
				<text class="text_2">选择支付方式</text>
				<view class="justify-between group_6" v-for="(item,index) in payment" @tap="paytype=item.sign">
					<view class="flex-row">
						<image :src="item.logo" class="image_8" />
						<text class="text_6">{{item.name}}</text>
					</view>
					<image src="/static/local/5d02b47de7d570a6fcfcbb4d3e9ca5b4.png" v-if="paytype == item.sign"
						class="image_4" />
					<image src="/static/local/bd0de805aca0fec835ae680a644b85e2.png" v-else class="image_4 image_9" />
				</view>
				<view class="justify-between group_6" @tap="paytype='studyCoin'">
					<view class="flex-row">
						<image src="/static/local/16403089588172074136.png" class="image_8" />
						<text class="text_6">学习币支付</text>
						<text class="text_7">(余额：{{coin}})</text>
					</view>
					<image src="/static/local/5d02b47de7d570a6fcfcbb4d3e9ca5b4.png" v-if="paytype == 'studyCoin'"
						class="image_4" />
					<image src="/static/local/bd0de805aca0fec835ae680a644b85e2.png" v-else class="image_4 image_9" />
				</view>
			</view>
			<!-- vk万能支付组件 -->
			<vk-uni-pay debug :auto-get-openid='false' ref="vkPay" :query-payment-action="vkPay.queryPaymentAction"
				:status.sync="vkPay.status" :code-url.sync="vkPay.codeUrl" :page-show="vkPay.pageShow"
				:polling="vkPay.polling"></vk-uni-pay>
		</view>
		<view class="flex-col items-center button" @tap="doDeposit">
			<image src="/static/local/a20c0f08ae32a0faa0fadd9155be195b.png" class="image_10" />
		</view>

		<u-toast ref="uToast" />

		<u-keyboard ref="uKeyboard" mode="number" v-model="show" :dot-enabled="false" :tooltip="false"
			@change="valChange" @backspace="backspace">
			<template v-slot:default>
				<view class="input_six_box">
					<view class="title">请输入支付密码</view>
					<view class="desc">{{content}}</view>
					<u-message-input :value="value" :width="80" dot-fill breathe :maxlength="6"
						:disabled-keyboard="true">
					</u-message-input>
				</view>
			</template>
		</u-keyboard>

		<u-modal v-model="pswPop" show-cancel-button confirm-text="重试" :cancel-text="canText" @confirm="confirm"
			@cancel="cancel" ref="uModal" :content="showText"></u-modal>
	</view>
</template>

<script>
	import vkUniPay from "@/uni_modules/vk-uni-pay/components/vk-uni-pay/vk-uni-pay"
	let time = null;
	var that; // 当前页面对象
	var vk; // vk依赖
	export default {
		components: {
			vkUniPay
		},
		data() {
			return {
				orderId: 0,
				order: {
					title: '',
					total_fee: 0
				},
				goods: {},
				paytype: 'studyCoin', //支付类型,
				payment: [],
				vkPay: {
					/**
					 * 查询支付状态的云函数配置
					 * 如果是非路由框架，则action为字符串，值为云函数名称
					 * 如果是路由框架，则按下方配置填写
					 */
					queryPaymentAction: {
						name: "router", // 云函数名称
						action: "client/payment/kh/query", // 路由模式下云函数地址
						actionKey: "$url", // 路由模式下云函数地址的识别key
						dataKey: "data" // 路由模式下云函数请求参数的识别key
					},
					// PC支付的付款二维码地址
					codeUrl: "",
					// 当前支付状态 0:等待发起支付 1:支付中 2:已支付
					status: 0,
					// 当前页面是否显示
					pageShow: true,
					// 启用轮询检测订单支付状态（仅h5支付有效）
					polling: true
				},
				// 学习币数量
				coin: '',
				show: false,
				content: '',
				// 换算率
				proportion: 10,
				// 支付密码
				value: '',
				canText: '取消',
				times: 5,

				pswPop: false
			};
		},
		onLoad(option) {
			that = this;
			vk = that.vk;
			this.orderId = option.order_id
			this.getOrder()
			this.getUserInfo()
		},
		onUnload() {
			if (time != null) clearInterval(time)
		},
		watch: {
			show() {
				if (!this.show) this.$nextTick(() => {
					this.value = ''
				})
			},
			value() {
				if (this.value.length > 5) {
					this.show = false
					vk.callFunction({
						url: 'client/accout/kh/checkPaymentPsw',
						title: '检验支付密码...',
						needAlert: false,
						data: {
							paymentPsw: that.value,
							need_user_info: true
						},
						success: function(data) {
							that.useCoin()
						},
						fail: function(data) {
							that.pswPop = true
						}
					})
				}
			}
		},
		computed: {
			showText() {
				if (this.times < 1) return `支付密码错误,请重试!`
				return `支付密码错误,请重试!(剩余${this.times}次)`
			}
		},
		methods: {
			//根据订单号查询出订单详情
			getOrder() {
				uni.vk.callFunction({
					url: 'client/order/kh/detail',
					data: {
						"_id": this.orderId
					},
					success(res) {
						that.order = res.data.order;
						that.goods = res.data.goods;
						that.payment = res.data.payment

						//如果是免费订单 直接支付成功
						if (that.order.total_fee == 0) {
							uni.redirectTo({
								url: './success?amount=' + (that.order.total_fee / 100.0) + '&type=1'
							});
						}

						//如果已经成功支付 则关闭 返回上一页
						if (that.order.status == 2) {
							if (time != null) {
								clearInterval(time);
								uni.hideLoading()
							}
							uni.redirectTo({
								url: './success?amount=' + (that.order.total_fee / 100.0) + '&type=1'
							});
						}
					}
				})
			},
			getUserInfo() {
				// 所持学习币
				uni.vk.userCenter.getCurrentUserInfo({
					success: function(data) {
						that.coin = data.userInfo.coin
					}
				})
				// 换算率
				vk.callFunction({
					url: 'client/dictionary-table/pub/getList',
					title: '请求中...',
					success: function(data) {
						let a = vk.pubfn.getListItem(data.rows, 'dictionary_id', 'coin-proportion')
						that.proportion = a.number
					}
				});
			},
			doDeposit() {
				if (this.paytype == '') return uni.showToast({
					icon: "none",
					title: '请选择支付方式'
				})

				let that = this

				if (this.paytype == 'studyCoin') {
					let num = that.proportion * that.order.total_fee / 100
					if (num > this.coin) return uni.showToast({
						icon: "none",
						title: '学习币不足！'
					})
					uni.vk.userCenter.getCurrentUserInfo({
						success: function(data) {
							if (vk.pubfn.isNull(data.userInfo.payment_psw)) {
								that.$refs.uToast.show({
									title: '请前往设置支付密码',
									type: 'warning',
									duration: 800,
									url: '/pages/mine/setting/payment-password'
								})
								return
							}
							that.content = `使用${that.proportion * that.order.total_fee / 100}学习币购买课程`
							that.show = true
							return
						}
					})
				}
				//官方支付
				if (this.paytype == 'wxpay' || this.paytype == 'alipay') {
					console.log(1)
					let clientType = 'h5'
					// // #ifdef MP-WEIXIN
					clientType = 'mp'
					// // #endif

					this.$refs.vkPay.createPayment({
						// 如果是非路由框架，则action为字符串，值为云函数名称
						// 如果是路由框架，则按下方配置填写
						action: {
							name: "router", // 云函数名称
							action: "client/payment/kh/create", // 路由模式下云函数地址
							actionKey: "$url", // 路由模式下云函数地址的识别key(注意VK路由框架下,此值为$url)
							dataKey: "data" // 路由模式下云函数请求参数的识别key
						},
						data: {
							provider: this.paytype,
							oid: this.orderId,
							clientType: clientType,
							// openid: uni.getStorageSync('openid')
							// openid: ''
						},
						create: res => {
							console.log(res)
						},
						success: res => {
							this.changeData(this.orderId)
						},
						// 失败回调
						fail: res => {
							if (res.failType === "create") {
								// 创建支付失败时提示
								this.toast(res.msg);
							} else if (res.failType === "request") {
								// 请求支付失败时提示
								this.toast("请求支付失败");
							} else if (res.failType === "result") {
								// 支付结果失败时提示
								this.toast("支付失败");
							}
						},
						// 取消回调
						cancel: res => {
							this.toast("用户取消支付");
						}
					})
				}
				//YunGouOS支付
				if (this.paytype == 'YunGouOS_wxpay' || this.paytype == 'YunGouOS_alipay') {
					uni.vk.callFunction({
						url: 'client/payment/kh/create',
						title: "支付中...",
						data: {
							provider: this.paytype,
							oid: this.orderId
						},
						success(res) {
							//拉起支付
							if (res.platform == 'MP-WEIXIN' && res.paytype == 'YunGouOS_wxPay') {
								that.YunGouOS_wxPay_minapp(res.params)
							} else {
								that.YunGouOS_h5Pay(res.params)
							}
						}
					});
				}
			},
			YunGouOS_h5Pay(data) {
				uni.showToast({
					icon: "loading",
					title: "准备支付ing..."
				})
				// #ifdef H5
				window.location.href = data
				// #endif

				// #ifndef H5
				let wv = plus.webview.create("", "pay-webview", {
					plusrequire: "none",
					'uni-app': 'none',
				});
				wv.loadURL(data, {
					Referer: 'http://www.yungouos.com'
				});
				var currentWebview = this.$scope.$getAppWebview();
				currentWebview.append(wv);
				wv.hide();
				//轮询查询自己系统的订单状态
				uni.showLoading({
					title: "支付中..."
				})
				time = setInterval(() => {
					this.getOrder()
				}, 1000)
				// #endif
			},
			YunGouOS_wxPay_minapp(data) {
				let that = this
				wx.navigateToMiniProgram({
					appId: 'wxd9634afb01b983c0', //支付收银小程序的appid 固定值 不可修改
					path: '/pages/pay/pay', //支付页面 固定值 不可修改
					extraData: data, //携带的参数 参考API文档
					success(res) {
						//支付成功
						uni.redirectTo({
							url: './success?amount=' + (that.order.total_fee / 100.0) + '&type=1'
						});
					}
				});
			},
			// 按键被点击(点击退格键不会触发此事件)
			valChange(val) {
				if (this.value.length > 5) return
				this.value += val
			},
			// 退格键被点击
			backspace() {
				if (this.value.length) this.value = this.value.substr(0, this.value.length - 1);
			},
			useCoin() {
				let num = that.proportion * that.order.total_fee / 100
				vk.callFunction({
					url: 'client/accout/kh/useCoin',
					title: '购买中...',
					data: {
						order_id: that.orderId,
						useOrRecharge: 'use',
						amount: num,
						need_user_info: true
					},
					success: function(data) {
						//支付成功
						uni.redirectTo({
							url: './success?amount=' + (that.order.total_fee / 100.0) + '&type=1'
						})
					}
				})
			},
			confirm() {
				this.show = true
				setTimeout(() => {
					this.times -= 1
					if (this.times < 1) this.canText = '忘记密码'
				}, 200)
			},
			cancel() {
				if (this.times < 5) {
					this.$nextTick(() => {
						vk.navigateTo('/pages/mine/setting/payment-password');
						this.canText = '取消'
						this.times = 5
					})
				}
			},
			changeData(orderId) {
				vk.callFunction({
					url: 'client/order/kh/payChange',
					title: '请求中...',
					data: {
						need_user_info: true,
						order_id: orderId
					},
					success: function(data) {
						let url = './success?amount=' + (that.order.total_fee / 100.0) + '&type=1'
						setTimeout(() => {
							vk.redirectTo(url)
						}, 500)
					}
				});
			}
		}
	}
</script>

<style lang="scss">
	uni-page-body {
		height: 100%;
	}

	.group_1 {
		padding: 20rpx 20rpx 0;
		height: 100%;
		box-sizing: border-box;
		flex: 1 1 auto;
		overflow-y: auto;
		background-color: #F4F6F9;

		.button {
			margin: 240rpx 30rpx 0;
			padding: 21rpx 0 20rpx;
			background-color: rgb(51, 51, 51);
			border-radius: 40rpx;

			.image_10 {
				filter: drop-shadow(0px 6rpx 6rpx rgba(0, 143, 255, 0.16));
				width: 130rpx;
				height: 40rpx;
			}
		}

		.text-wrapper {
			padding: 40rpx 0 34rpx;
			color: rgb(51, 51, 51);
			font-size: 32rpx;
			line-height: 38rpx;
			white-space: nowrap;
			background-color: rgb(255, 255, 255);
			border-radius: 12rpx;

			.text_1 {
				margin-left: 20rpx;
			}
		}

		.section_1 {
			margin-top: 20rpx;
			padding: 36rpx 20rpx 51rpx;
			background-color: rgb(255, 255, 255);
			border-radius: 12rpx;

			.text_2 {
				color: rgb(51, 51, 51);
				font-size: 32rpx;
				line-height: 38rpx;
				white-space: nowrap;
			}

			.group_6 {
				margin-top: 62rpx;
				padding-left: 21rpx;
				padding-right: 18rpx;

				.image_9 {
					margin: 4rpx 0;
				}

				.image_8 {
					width: 49rpx;
					height: 48rpx;
				}

				.text_6 {
					margin: 5rpx 0 5rpx 23rpx;
					color: rgb(51, 51, 51);
					font-size: 32rpx;
					line-height: 38rpx;
					white-space: nowrap;
				}

				.text_7 {
					align-self: center;
					color: rgb(153, 153, 153);
					font-size: 24rpx;
					line-height: 29rpx;
					white-space: nowrap;
				}
			}

			.image_4 {
				width: 40rpx;
				height: 40rpx;
			}
		}
	}

	.input_six_box {
		background-color: #FFFFFF;
		margin: 0 60rpx 15vh;
		border-radius: 10rpx;
		text-align: center;
		padding-bottom: 40rpx;

		.title {
			font-size: 32rpx;
			font-weight: bold;
			padding-top: 40rpx;
		}

		.desc {
			font-size: 24rpx;
			margin: 20rpx 0 40rpx;
		}
	}

	/deep/ .u-drawer-bottom {
		background-color: transparent !important;
	}

	/deep/ .u-keyboard {
		background-color: #FFFFFF;
	}
</style>